<template>
  <div class="main">
    <div :id="cid" class="item"></div>
    <el-card class="item sub">
      <div v-for="o in 4" :key="o">
        {{'图标说明 ' + o }}
      </div>
    </el-card>
  </div>
</template>

<script>
import * as d3 from 'd3';
import 'd3-scale'
import 'd3-shape'
import 'd3-array'
import 'd3-selection'
// import data from '../data/data.json'

export default {
  name: "ParallelCoordinates",
  props:['cid','height'],
  mounted() {
    this.axios.get('http://localhost:5000/api/data').then(res=>{
      this.draw(res.data)
    })

  },
  methods:{
    draw(data){
      data.columns = Object.keys(data[0])
      let keys = data.columns.splice(1),
          width = 1000,
          height = keys.length * 120,
          margin = ({top: 20, right: 10, bottom: 20, left: 10}),
          x = new Map(Array.from(keys, key => [key, d3.scaleLinear(d3.extent(data, d => d[key]), [margin.left, width - margin.right])])),
          y = d3.scalePoint(keys, [margin.top, height - margin.bottom]);
      let    z = d3.scaleSequential(x.get('cylinders').domain(), t => d3.interpolateBrBG(1 - t)),
          line = d3.line()
              .defined(([, value]) => value != null)
              .x(([key, value]) => x.get(key)(value))
              .y(([key]) => y(key));

      const svg = d3.select(`#${this.cid}`).append("svg")
          .attr("viewBox", [0, 0, width, height]);

      svg.append("g")
          .attr("fill", "none")
          .attr("stroke-width", 1.5)
          .attr("stroke-opacity", 0.4)
          .selectAll("path")
          .data(data.slice().sort((a, b) => d3.ascending(a['cylinders'], b['cylinders'])))
          .join("path")
          .attr("stroke", d => z(d['cylinders']))
          .attr("d", d => line(d3.cross(keys, [d], (key, d) => [key, d[key]])))
          .append("title")
          .text(d => d.name);

      svg.append("g")
          .selectAll("g")
          .data(keys)
          .join("g")
          .attr("transform", d => `translate(0,${y(d)})`)
          .each(function(d) { d3.select(this).call(d3.axisBottom(x.get(d))); })
          .call(g => g.append("text")
              .attr("x", margin.left)
              .attr("y", -6)
              .attr("text-anchor", "start")
              .attr("fill", "currentColor")
              .text(d => d))
          .call(g => g.selectAll("text")
              .clone(true).lower()
              .attr("fill", "none")
              .attr("stroke-width", 5)
              .attr("stroke-linejoin", "round")
              .attr("stroke", "white"));

      return svg.node();
    }
  }
}
</script>

<style scoped>
.main{
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-end
}
.item{
  flex-grow:1;
  flex-shrink:1;
}
.sub{
  max-width: 300px;
  min-width: 200px;
  flex-grow:1;
  flex-shrink:0;
}
</style>